# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_fuzhou_zfxxgk_policy'

    province = '福建省'
    city = '福州市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ["福州市人民政府", "", "https://www.fuzhou.gov.cn/zfxxgkzl/szfbmjxsqxxgk/szfbmxxgk/fzsrmzf/zc/gfxwj/list.htm"],
        ]:
            yield scrapy.Request(url, callback=self._parser_dataproxy_html,
                                 meta={"item": {'source': source, 'county': county}})

    def _parser_dataproxy_html(self, response):
        meta = response.meta
        ul = response.xpath('.')
        
        channelid = ul.re_first(r"""channelid:\s*["']?(.*?)["']?,""")
        classsql1 = ul.re_first(r"""classsql:\s*["']?(.*?)["']?,""").split('" || "')
        if len(classsql1) == 2:
            classsql = classsql1[0] if classsql1[0] != '"' and classsql1[0] else classsql1[1]
        else:
            classsql = classsql1[-1]
        classcol = ul.re_first(r"""classcol:\s*["']?(.*?)["']?,""")
        if channelid == 'SiteInfo.searchId':
            channelid = ul.re_first(r"""searchId\s*:\s*["']?(\d+)["']?,?\s*""")
        data = {
            'sortfield': '-docorder,-docreltime',
            'channelid': str(channelid),
            'classsql': str(classsql),
            'classcol': str(classcol),
            'classnum': str(100),
            'classsort': str(0),
            # 'cache': True,
            'prepage': str(75),
            'page': str(1),
        }
        temp_url = response.urljoin('/fjdzapp/search')
        meta.update({
            "data": data,
        })
        print(data)
        yield self.FormRequest(
            temp_url,
            formdata=data,
            method="POST",
            callback=self.parse_list,
            dont_filter=True,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        url_list = response.json()['data']
        for elem in url_list:
            item = Item()
            item['source_url'] = elem['chnldocurl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubdate'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_page = int(response.json()['pageCount'])
        print(meta['data'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1)):
            data = meta.get("data")
            data['page'] = str(page)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {data}")
            yield self.FormRequest(
                response.url,
                formdata=meta['data'],
                method="POST",
                meta=meta,
                callback=self.parse_list,
                dont_filter=True
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_fuzhou_zfxxgk_policy -a get_next=0".split())
